<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\fetch\kuaishou;

use app\enum\CommonEnum;
use app\enum\ConfigEnum;
use app\enum\KuaiShouEnum;
use app\model\ClientAccountModel;
use app\model\KsCreativeTagModel;
use app\service\client\AccountService;
use app\service\fetch\MediaInterface;
use app\service\fetch\MediaService;
use app\service\kuaishou\AdvertiserService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;

final class CreativeTagService extends MediaService implements MediaInterface
{
    /**
     * @var string 数据拉取key
     */
    protected const FETCH_KEY = ConfigEnum::CACHE_CONFIG[KuaiShouEnum::LIST_CONFIG_LOCK_KEY]['creative_tag'];

    /**
     * 创意标签.
     *
     * @param string $advertiserId 广告主id
     */
    public static function getCreativeTag(string $advertiserId = ''): bool
    {
        try {
            // 获取账户信息
            $obj = AccountService::getAccountModel(0, $advertiserId);
            if (! $obj instanceof ClientAccountModel || ! $obj->getKey()) {
                return self::setError('账户数据不存在');
            }

            $result = self::getList($advertiserId);
            if ($result === false) {
                return false;
            }
            if (count($result['data']) == 0) {
                return true;
            }
            foreach ($result['data'] as $item) {
                $model = self::getInfo($advertiserId, $item['industry'], $item['secondIndustry']);
                if (! $model instanceof KsCreativeTagModel || ! $model->getKey()) {
                    $model = new KsCreativeTagModel();
                }
                $item['advertiser_id'] = $advertiserId;
                $item['account_id'] = $obj->getKey();
                $item['tags'] = json_encode($item['tags'], JSON_UNESCAPED_UNICODE);

                $model->setAttrs($item);
                if (! $model->save()) {
                    throw new \Exception('保存数据出错');
                }
            }

            return true;
        } catch (\Exception $e) {
            return self::setError($e->getMessage());
        }
    }

    /**
     * 获取创意标签.
     *
     * @param string $advertiserId 账户id
     * @return bool|mixed|string
     */
    private static function getList(string $advertiserId = '')
    {
        $token = AccountService::getToken(CommonEnum::KS_MEDIA, $advertiserId);
        if (! $token) {
            return self::setError('token获取失败');
        }
        $headers = [
            'Access-Token' => $token,
            'Content-Type' => 'application/json',
        ];
        $params = [
            'advertiser_id' => $advertiserId,
        ];
        return AdvertiserService::getCreativeTag($headers, $params);
    }

    /**
     * 获取创意标签信息.
     * @param string $advertiserId 账户id
     * @param string $industry 一级行业
     * @param string $secondIndustry 二级行业
     * @return null|array|KsCreativeTagModel|mixed|Model
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private static function getInfo(string $advertiserId = '', string $industry = '', string $secondIndustry = '')
    {
        $where = [
            ['advertiser_id', '=', $advertiserId],
            ['industry', '=', $industry],
            ['secondIndustry', '=', $secondIndustry],
        ];
        return (new KsCreativeTagModel())->where($where)->field(true)->find();
    }
}
